package com.up.upzl.biz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.up.upzl.base.service.impl.BaseServiceImpl;
import com.up.upzl.biz.domain.User;
import com.up.upzl.biz.domain.User.Platform;
import com.up.upzl.biz.domain.User.Status;
import com.up.upzl.biz.repository.UserRepository;
import com.up.upzl.biz.service.UserService;

import utils.UpzlUtils;

@Service
public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService {

	@Autowired
	private UserRepository userRepository;

	public Page<User> findByCondition(String account, Platform platform, Date beginTime, Date endTime, Pageable page) {
		return userRepository.findAll(new Specification<User>() {
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();

				if (!StringUtils.isEmpty(account))
					predicates.add(cb.and(cb.like(root.get("account"), "%" + account + "%")));
				if (platform != null)
					predicates.add(cb.and(cb.equal(root.get("platform"), platform)));
				if (beginTime != null)
					predicates.add(cb.and(cb.greaterThanOrEqualTo(root.get("firstTime"), beginTime)));
				if (endTime != null)
					predicates.add(cb.and(cb.lessThanOrEqualTo(root.get("firstTime"), UpzlUtils.timeHelper(endTime))));
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, page);
	}

	@Override
	public User findByAccount(String account) {
		return userRepository.findByAccount(account);
	}

	@Override
	public User editUser(User user) {
		if(Objects.isNull(user.getLoginCount())) {
			user.setLoginCount(0);
		}
		if(Objects.isNull(user.getStatus())) {
			user.setStatus(Status.正常);
		}
	    userRepository.save(user);
	    return user;
	}
}
